<!--
 * @FilePath: CommData.vue
 * @Author: 杜芬
 * @Date: 2025-04-26 16:42:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-04-26 18:33:26
 * Copyright: 2025 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 页面
-->
<template>
  <div class="info-list">
    <h3>我是infoList组件</h3>
    <el-button type="primary" @click="add">新增</el-button>
    <el-table
      style="width:100%"
      :data="tableData"
      border
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column prop="name" property="name" label="商品名称" width="180" />
      <el-table-column prop="price" property="price" label="商品价格" width="180" />
      <el-table-column prop="count" property="count" label="数量" width="180">
        <template slot-scope="{ row, $index }">
          <el-button
            size="mini"
            :disabled="row.count <= 1"
            @click="reduce($index)"
          >-
          </el-button>
          {{ row.count }}
          <el-button
            size="mini"
            @click="addNum($index)"
          >+
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <AddDialog :dialog-visible="dialogVisible" @closeDialog="closeDialog" />
  </div>
</template>
<script>

import AddDialog from '@/views/tableTwo/components/AddDialog.vue'
export default {
  name: 'InfoList',
  components: { AddDialog },
  props: {
    activeName: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      dialogVisible: false,
      tableData: [
        { id: 1, name: '商品A', price: 100, count: 2 },
        { id: 2, name: '商品B', price: 200, count: 1 },
        { id: 3, name: '商品C', price: 150, count: 3 }
      ]
    }
  },
  created() {
  },
  methods: {
    // 新增
    add() {
      console.log('新增')
      this.dialogVisible = true
    },
    closeDialog() {
      this.dialogVisible = false
    },
    getSummaries({ columns, data }) {
      console.log(columns, data, 'columns, data的最新的值')
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计' // 首列标题
          return
        }
        if (column.property === 'count') { // 指定统计列
          const values = data.map(item => Number(item[column.property]))
          sums[index] = values.reduce((prev, curr) => prev + curr, 0)
        } else {
          sums[index] = '' // 非统计列留空
        }
      })
      return sums
    },
    addNum(index) {
    // 直接修改数组项需要深拷贝触发响应式
      const newRow = JSON.parse(JSON.stringify(this.tableData[index]))
      newRow.count++
      this.$set(this.tableData, index, newRow)
    },
    reduce(index) {
      if (this.tableData[index].count <= 1) return
      const newRow = JSON.parse(JSON.stringify(this.tableData[index]))
      newRow.count--
      this.$set(this.tableData, index, newRow)
    }
  }
}
</script>
